package com.hy.chat.client.presenter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.hy.chat.client.Chat;
import com.hy.chat.client.ChatServiceAsync;
import com.hy.chat.client.widget.ChatTabItem;

public class AdminChatPersenter implements Presenter{
	
	private Display display;
	private ChatServiceAsync greetingService= Registry.get(Chat.CHAT_SERVICE);
	private static final String  ICON = "myGwt-image1";

//	private Panel panel;
	
	public AdminChatPersenter(Panel panel,Display display) {
		super();
		this.display = display;
		//this.panel = panel;
		this.bind();
	}

	public AdminChatPersenter(Display display) {
		super();
		this.display = display;
		//this.panel = panel;
		this.bind();
	}
	public interface Display{
		public Button	getSentButton() ;
		public TabPanel	getTabPanel() ;
		public HtmlEditor	getHtmlEditor() ;
	    public Widget asWidget();

	}
	

	@Override
	public void go(HasWidgets container) {
		container.add(display.asWidget());
	}
	
	public void bind() {
		
		this.sentMessage();
		this.repeatSentMessage();
	}
	
	private void callAdminChatService(List<BaseModel> list,final HtmlEditor htmlEditor,final TabPanel	 folder) {
		
		greetingService.getAdminIndexAndMessage(list,  new AsyncCallback<List<BaseModel>>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("*** "+GWT.getModuleBaseURL()+"chatService");

				MessageBox.alert("警告",	"后台的Rpc调用失败，请联系管理员或者稍后再试！", null);
			}

			@Override
			public void onSuccess(List<BaseModel> returnBaseModelList) {											
				
				if (htmlEditor!=null) {
					htmlEditor.setValue("");
					//htmlEditor.focus();
				}
				for (BaseModel indexAndMessage : returnBaseModelList) {
					String sessionId = indexAndMessage.get("sessionId");
					//folder.getItems();
					//判断是否存在与之对应的TabItem
					//如果存在，则赋值
					//如果不存在，则创建新的TabItem
					boolean flag = false;
					for(TabItem tempTabItem :folder.getItems()){
						ChatTabItem tabItem= (ChatTabItem)tempTabItem;
						if (sessionId.equals(tabItem.getData("sessionId"))) {
						//	tabItem.focus();
							flag = true;
							
							   
							    String string = tabItem.getHtml().getHtml();
							    tabItem.setData("messageIndex", indexAndMessage.get("index"));
								if (indexAndMessage.get("message")==null||indexAndMessage.get("message").equals("")) {

								}else {

								    tabItem.getHtml().setHtml(string+"<br>"+indexAndMessage.get("message"));

								}

							    indexAndMessage.set("index", tabItem.getData("messageIndex"));
							/*if (folder.getSelectedItem().getId().equals(tabItem.getId())) {
								indexAndMessage.set("message", htmlEditor.getValue());
								
							}*/
							indexAndMessage.set("sessionId", tabItem.getData("sessionId"));
													}
					
					}
					if (!flag) {
						folder.add(createChatTabItem(sessionId,indexAndMessage.get("message").toString(),(Integer)indexAndMessage.get("index"),true));
					}
				}
				
				

//				if (returnBaseModel.get("sessionId")!=null) {
//					folder.add(new TabItem());
//				}
				
				
			}
		});
	}
	
	
	private String getCurrentDateTime() {
		return DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_SHORT).format(new Date());
	}
	
	
	private ChatTabItem createChatTabItem (String sessionId,String message,int index,boolean closable) {
		ChatTabItem chatTabItem = new ChatTabItem("与客户"+sessionId.substring(0, 6)+"会话");  
		    chatTabItem.addStyleName("pad-text");  
		    chatTabItem.setHeight(100);  
		    chatTabItem.setIconStyle(ICON);

		    chatTabItem.setData("messageIndex", index);
		    chatTabItem.setData("sessionId", sessionId);
		    chatTabItem.setClosable(closable);
//		    chatTabItem.addText(message);  
		    chatTabItem.setScrollMode(Scroll.AUTOY); 

		    Html xx =chatTabItem.addText(message);  
		   // chatTabItem.focus();
		    return chatTabItem;
	}
	
	private void sentMessage() {
		//为按钮，用于完成：1提交和返回数据2清空文本编辑器
		display.getSentButton().addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				
				//MessageBox.alert("提示",	"发送成功！", null);

				display.getTabPanel().getItems();
				System.out.println("=================="+display.getTabPanel().getSelectedItem().getId());
				List<BaseModel> list = new ArrayList<BaseModel>();

				for(TabItem tabItem :display.getTabPanel().getItems()){
					BaseModel indexAndMessage = new BaseModel();
					indexAndMessage.set("index", tabItem.getData("messageIndex"));
					String preStr = "客服说："+getCurrentDateTime()+"<br>";
					//为当前正在编辑的htmlEditor，和与之相对应的tabItem建立一一对应关系
					if (display.getTabPanel().getSelectedItem().getId().equals(tabItem.getId())) {
						indexAndMessage.set("message", preStr+display.getHtmlEditor().getValue());
						
					}
					
					indexAndMessage.set("sessionId", tabItem.getData("sessionId"));
					list.add(indexAndMessage);
					
				}
				
				callAdminChatService(list, display.getHtmlEditor(), display.getTabPanel());
				
																					
			}
		});
	}

	
	private BaseModel encapsulateIndexAndMessage() {
		return null;
	}
	
	private void repeatSentMessage() {
		final Timer t = new Timer() {  
	        
			@Override  
	        public void run() { 
				List<BaseModel> list = new ArrayList<BaseModel>();

				for(TabItem tabItem :display.getTabPanel().getItems()){
					BaseModel indexAndMessage = new BaseModel();
					indexAndMessage.set("index", tabItem.getData("messageIndex"));
					
					
					indexAndMessage.set("sessionId", tabItem.getData("sessionId"));
					list.add(indexAndMessage);
					System.out.println("re indexAndMessage sessionId "+ indexAndMessage.get("sessionId")+
							"index is "+indexAndMessage.get("index"));
				}
				

				callAdminChatService(list, null, display.getTabPanel());
	        		        	
	        }  
	      }; 
	      
	    
		      t.scheduleRepeating(1000);  
	}
}
